package cn.itsource.service.impl;

import cn.itsource.bean.*;
import cn.itsource.config.PageList;
import cn.itsource.mapper.PetMapper;
import cn.itsource.query.PetQuery;
import cn.itsource.service.*;
import cn.itsource.util.JsonResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

import static cn.itsource.util.PetHomeConstant.PET.*;

/**
 * @author : 张金铭
 * @description :
 * @create :2022-11-23 10:17:00
 */
@Service
public class PetServiceImpl extends ServiceImpl<PetMapper, Pet> implements IPetService {

    @Resource
    private IShopService shopService;

    @Resource
    private IPetTypeService petTypeService;

    @Resource
    private IUserService userService;

    @Resource
    private PetMapper petMapper;

    @Resource
    private IPetDetailService petDetailService;

    @Resource
    private IEmployeeService employeeService;


    @Override
    public JsonResult getPage(PetQuery query) {
        Page<Pet> page = new Page<>(query.getPage(),query.getRows());

        LambdaQueryWrapper<Pet> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(Strings.isNotEmpty(query.getStartTime()),Pet::getCreateTime,query.getStartTime()).
                le(Strings.isNotEmpty(query.getEndTime()),Pet::getCreateTime,query.getEndTime());
        queryWrapper.like(Strings.isNotEmpty(query.getKeyword()), Pet::getName,query.getKeyword())
                .or().like(Strings.isNotEmpty(query.getKeyword()),Pet::getResourceType,query.getKeyword());


        Page<Pet> messagePage = this.page(page, queryWrapper);
        List<Pet> records = messagePage.getRecords();

        records = records.stream().map(item->{
            Long shopId = item.getShopId();
            Long typeId = item.getTypeId();
            Long userId = item.getUserId();

            if (shopId!=null){
                Shop byId = shopService.getById(shopId);
                if (byId!=null){
                    item.setShopName(byId.getName());
                }
            }
            if (typeId!=null){
                PetType byId = petTypeService.getById(typeId);
                if (byId!=null){
                    item.setPetTypeName(byId.getName());
                }
            }
            if (userId!=null){
                User byId = userService.getById(userId);
                if (byId!=null){
                    item.setUserName(byId.getUsername());
                }else {
                    Employee emp = employeeService.getById(userId);
                    if (emp!=null){
                        item.setUserName(emp.getUsername());
                    }
                }
            }
            return item;
        }).collect(Collectors.toList());


        PageList<Pet> pageList = new PageList<>();
        pageList.setTotal(messagePage.getTotal());
        pageList.setList(records);
        return JsonResult.success(pageList);
    }

    @Override
    @Transactional
    public JsonResult add(Pet pet) {

        if (pet.getId()==null){
            //获取到数据后，将状态默认为下架
            pet.setState(PET_STATE_DOWN);

            //设置创建时间
            pet.setCreateTime(LocalDateTime.now());

            //先保存pet,获取到id
            petMapper.insert(pet);

            PetDetail detail = pet.getDetail();
            detail.setPetId(pet.getId());

            //存入商品详细信息表
            petDetailService.save(detail);
        }else {
            this.updateById(pet);
            PetDetail detail = pet.getDetail();
            //存入商品详细信息表
            petDetailService.updateById(detail);
        }


        return JsonResult.success("保存成功");
    }

    @Override
    @Transactional
    public JsonResult upState(PetQuery query,Long state) {
        List<Long> ids = query.getIds();
        //更改状态
        if (state==PET_STATE_DOWN){

            List<Pet> pets = this.listByIds(ids);
            pets = pets.stream().map(item->{
                item.setState(PET_STATE_DOWN);
                item.setOffsaletime(LocalDateTime.now());
                return item;
            }).collect(Collectors.toList());
            this.updateBatchById(pets);
        }else if (state == PET_STATE_UP){
            List<Pet> pets = this.listByIds(ids);
            pets = pets.stream().map(item->{
                item.setState(PET_STATE_UP);
                item.setOnsaletime(LocalDateTime.now());
                return item;
            }).collect(Collectors.toList());
            this.updateBatchById(pets);
        }else if (state == PET_STATE_BY){
            List<Pet> pets = this.listByIds(ids);
            pets = pets.stream().map(item->{
                item.setState(PET_STATE_UP);
                return item;
            }).collect(Collectors.toList());
            this.updateBatchById(pets);
        }

        return JsonResult.success("更改成功");
    }

    @Override
    public JsonResult getPetById(Long id) {
        //通过id获取具体数据
        Pet pet = this.getById(id);

        LambdaQueryWrapper<PetDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PetDetail::getPetId,id);
        PetDetail detail = petDetailService.getOne(queryWrapper);

        Long shopId = pet.getShopId();
        Long userId = pet.getUserId();
        Long typeId = pet.getTypeId();


        //通过查询填充数据
        if (shopId!=null){
            Shop byId = shopService.getById(shopId);
            if (byId!=null){
                pet.setShopName(byId.getName());
            }
        }
        if (userId!=null){
            User byId = userService.getById(userId);
            if (byId!=null){
                pet.setUserName(byId.getUsername());
            }else {
                Employee employee = employeeService.getById(id);
                if (employee!=null) {
                    pet.setUserName(employee.getUsername());
                }
            }
        }

        if (typeId!=null){
            PetType byId = petTypeService.getById(typeId);
            if (byId!=null){
                pet.setPetTypeName(byId.getName());
            }
        }

        if (detail!=null) {
            pet.setDetail(detail);
        }else {
            PetDetail petDetail = new PetDetail();
            pet.setDetail(petDetail);
        }

        return JsonResult.success(pet);
    }
}
